#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
项目分析器 - 分析用户项目的package.json和路由配置
"""

import os
import json
import re
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple

class ProjectAnalyzer:
    """项目分析器"""
    
    def __init__(self):
        print("🔍 项目分析器初始化完成")
    
    def analyze_package_json(self, package_json_path: str) -> Dict[str, Any]:
        """分析package.json文件"""
        print(f"\n📦 分析 package.json: {package_json_path}")
        
        if not os.path.exists(package_json_path):
            print(f"❌ package.json 文件不存在: {package_json_path}")
            return {}
        
        try:
            with open(package_json_path, 'r', encoding='utf-8') as f:
                package_data = json.load(f)
            
            analysis = {
                "project_name": package_data.get("name", "未知项目"),
                "version": package_data.get("version", "1.0.0"),
                "description": package_data.get("description", ""),
                "dependencies": package_data.get("dependencies", {}),
                "dev_dependencies": package_data.get("devDependencies", {}),
                "scripts": package_data.get("scripts", {}),
                "detected_framework": self._detect_ui_framework(package_data),
                "detected_libraries": self._detect_common_libraries(package_data),
                "project_type_hints": self._analyze_project_type(package_data)
            }
            
            print(f"✅ 项目分析完成:")
            print(f"   - 项目名称: {analysis['project_name']}")
            print(f"   - 版本: {analysis['version']}")
            print(f"   - 检测到的框架: {analysis['detected_framework']}")
            print(f"   - 依赖库数量: {len(analysis['dependencies'])}")
            print(f"   - 开发依赖数量: {len(analysis['dev_dependencies'])}")
            
            return analysis
            
        except Exception as e:
            print(f"❌ 分析 package.json 失败: {e}")
            return {}
    
    def analyze_router_config(self, router_path: str) -> Dict[str, Any]:
        """分析路由配置文件"""
        print(f"\n🛤️  分析路由配置: {router_path}")
        
        if not os.path.exists(router_path):
            print(f"❌ 路由配置文件不存在: {router_path}")
            return {}
        
        try:
            with open(router_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            analysis = {
                "file_type": self._detect_file_type(router_path),
                "router_type": self._detect_router_type(content),
                "routes": self._extract_routes(content),
                "route_patterns": self._analyze_route_patterns(content),
                "components": self._extract_components(content)
            }
            
            print(f"✅ 路由分析完成:")
            print(f"   - 文件类型: {analysis['file_type']}")
            print(f"   - 路由器类型: {analysis['router_type']}")
            print(f"   - 发现的路由数量: {len(analysis['routes'])}")
            print(f"   - 组件数量: {len(analysis['components'])}")
            
            return analysis
            
        except Exception as e:
            print(f"❌ 分析路由配置失败: {e}")
            return {}
    
    def _detect_ui_framework(self, package_data: Dict[str, Any]) -> str:
        """检测UI框架"""
        dependencies = {**package_data.get("dependencies", {}), **package_data.get("devDependencies", {})}
        
        # Vue框架检测
        vue_indicators = ["vue", "@vue/cli", "vue-router", "@vue/router", "vuex","axios"]
        if any(dep in dependencies for dep in vue_indicators):
            return "vue"
        
        # React框架检测
        react_indicators = ["react", "react-dom", "react-router", "react-router-dom", "@types/react","axios"]
        if any(dep in dependencies for dep in react_indicators):
            return "react"
        
        return "unknown"
    
    def _detect_common_libraries(self, package_data: Dict[str, Any]) -> List[str]:
        """检测常用库"""
        dependencies = {**package_data.get("dependencies", {}), **package_data.get("devDependencies", {})}
        
        common_libraries = []
        
        # UI组件库
        ui_libs = {
            "element-plus": "Element Plus",
            "ant-design-vue": "Ant Design Vue",
            "antd": "Ant Design",
            "vuetify": "Vuetify",
            "@mui/material": "Material-UI",
            "bootstrap": "Bootstrap",
            "tailwindcss": "Tailwind CSS"
        }
        
        # 状态管理
        state_libs = {
            "vuex": "Vuex",
            "redux": "Redux",
            "@reduxjs/toolkit": "Redux Toolkit",
            "mobx": "MobX"
        }
        
        # 工具库
        util_libs = {
            "axios": "Axios",
            "lodash": "Lodash",
            "moment": "Moment.js",
            "dayjs": "Day.js",
            "echarts": "ECharts",
            "chart.js": "Chart.js"
        }
        
        all_libs = {**ui_libs, **state_libs, **util_libs}
        
        for dep, name in all_libs.items():
            if dep in dependencies:
                common_libraries.append(name)
        
        return common_libraries
    
    def _analyze_project_type(self, package_data: Dict[str, Any]) -> List[str]:
        """分析项目类型提示"""
        hints = []
        
        dependencies = {**package_data.get("dependencies", {}), **package_data.get("devDependencies", {})}
        scripts = package_data.get("scripts", {})
        name = package_data.get("name", "").lower()
        description = package_data.get("description", "").lower()
        
        # 根据依赖分析 - 统一归类为web_app
        if any(lib in dependencies for lib in ["echarts", "chart.js", "d3", "@antv/g2"]):
            hints.append("web_app")  # 数据可视化归类为Web应用
        
        if any(lib in dependencies for lib in ["@types/node", "express", "koa"]):
            hints.append("web_app")  # 后端相关归类为Web应用
        
        if "e-commerce" in description or "shop" in name or "cart" in name:
            hints.append("web_app")  # 电商平台归类为Web应用
        
        # 根据脚本分析
        if "build:admin" in scripts or "admin" in str(scripts):
            hints.append("web_app")  # 管理系统归类为Web应用
        
        return hints
    
    def _detect_file_type(self, file_path: str) -> str:
        """检测文件类型"""
        ext = Path(file_path).suffix.lower()
        if ext in [".js", ".mjs"]:
            return "javascript"
        elif ext in [".ts", ".tsx"]:
            return "typescript"
        elif ext in [".vue"]:
            return "vue"
        elif ext in [".jsx"]:
            return "jsx"
        else:
            return "unknown"
    
    def _detect_router_type(self, content: str) -> str:
        """检测路由器类型"""
        if "vue-router" in content or "createRouter" in content:
            return "vue-router"
        elif "react-router" in content or "BrowserRouter" in content:
            return "react-router"
        else:
            return "unknown"
    
    def _extract_routes(self, content: str) -> List[Dict[str, str]]:
        """提取路由信息"""
        routes = []
        
        # Vue Router 路由模式
        vue_route_pattern = r'{\s*path:\s*[\'"]([^\'"]+)[\'"]\s*,\s*name:\s*[\'"]([^\'"]+)[\'"]\s*,?\s*component'
        vue_matches = re.findall(vue_route_pattern, content)
        for path, name in vue_matches:
            routes.append({"path": path, "name": name, "type": "vue"})
        
        # React Router 路由模式
        react_route_pattern = r'<Route\s+path=[\'"]([^\'"]+)[\'"]\s+element'
        react_matches = re.findall(react_route_pattern, content)
        for path in react_matches:
            routes.append({"path": path, "name": path.replace("/", ""), "type": "react"})
        
        return routes
    
    def _analyze_route_patterns(self, content: str) -> Dict[str, Any]:
        """分析路由模式"""
        patterns = {
            "nested_routes": "/:" in content or "children:" in content,
            "dynamic_routes": "/:id" in content or ":id" in content,
            "query_params": "query" in content.lower(),
            "guards": "beforeEach" in content or "beforeEnter" in content,
            "lazy_loading": "import(" in content or "lazy" in content
        }
        
        return patterns
    
    def _extract_components(self, content: str) -> List[str]:
        """提取组件名称"""
        components = []
        
        # Vue 组件导入模式
        vue_import_pattern = r'import\s+(\w+)\s+from\s+[\'"][^\'"]*\.vue[\'"]'
        vue_matches = re.findall(vue_import_pattern, content)
        components.extend(vue_matches)
        
        # React 组件导入模式
        react_import_pattern = r'import\s+(\w+)\s+from\s+[\'"][^\'"]*[\'"]'
        react_matches = re.findall(react_import_pattern, content)
        components.extend(react_matches)
        
        return list(set(components))  # 去重

if __name__ == "__main__":
    # 测试项目分析器
    analyzer = ProjectAnalyzer()
    
    # 测试package.json分析
    test_package = {
        "name": "test-project",
        "version": "1.0.0",
        "dependencies": {
            "vue": "^3.0.0",
            "vue-router": "^4.0.0",
            "element-plus": "^2.0.0",
            "axios": "^0.27.0"
        }
    }
    
    print("🧪 测试项目分析功能...")
    result = analyzer._detect_ui_framework(test_package)
    print(f"检测到框架: {result}")
    
    libs = analyzer._detect_common_libraries(test_package)
    print(f"检测到库: {libs}")
